/**
  * Copyright 2017 JessYan
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
package com.ewhome.apartment.app;

import android.content.Context;
import android.text.TextUtils;

import com.ewhome.apartment.app.constant.AppConstant;
import com.ewhome.apartment.mvp.model.ApiException;
import com.jess.arms.http.GlobalHttpHandler;
import com.jess.arms.http.RequestInterceptor;
import com.jess.arms.utils.DataHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Observable;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import timber.log.Timber;

/**
 * ================================================
 * 展示 {@link GlobalHttpHandler} 的用法
 * <p>
 * Created by JessYan on 04/09/2017 17:06
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public class GlobalHttpHandlerImpl implements GlobalHttpHandler {
    private Context context;
    static {
        //加载库文件
        System.loadLibrary("native-lib");
    }
    public GlobalHttpHandlerImpl(Context context) {
        this.context = context;
    }

    @Override
    public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
                    /* 这里可以先客户端一步拿到每一次http请求的结果,可以解析成json,做一些操作,如检测到token过期后
                       重新请求token,并重新执行请求 */
        try {
            if (!TextUtils.isEmpty(httpResult) && RequestInterceptor.isJson(response.body().contentType())) {
                JSONObject json = new JSONObject(httpResult);
                int code = json.getInt("code");
                if (code > 0) {
                    String msg=json.getString("msg");
                    throw new ApiException(code,msg);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return response;
        }


                 /* 这里如果发现token过期,可以先请求最新的token,然后在拿新的token放入request里去重新请求
                    注意在这个回调之前已经调用过proceed,所以这里必须自己去建立网络请求,如使用okhttp使用新的request去请求
                    create a new request and modify it accordingly using the new token
                    Request newRequest = chain.request().newBuilder().header("token", newToken)
                                         .build();

                    retry the request

                    response.body().close();
                    如果使用okhttp将新的请求,请求成功后,将返回的response  return出去即可
                    如果不需要返回新的结果,则直接把response参数返回出去 */

        return response;
    }

    // 这里可以在请求服务器之前可以拿到request,做一些操作比如给request统一添加token或者header以及参数加密等操作
    @Override
    public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
                    /* 如果需要再请求服务器之前做一些操作,则重新返回一个做过操作的的request如增加header,不做操作则直接返回request参数
                       return chain.request().newBuilder().header("token", tokenId)
                              .build(); */
                        String encodeString="";
                       RequestBody body=request.newBuilder().build().body();
                       if (body!=null&&RequestInterceptor.isParseable(body.contentType())){
                           try {
                               Buffer requestbuffer = new Buffer();
                               body.writeTo(requestbuffer);
                               Charset charset = Charset.forName("UTF-8");
                               MediaType contentType = body.contentType();
                               if (contentType != null) {
                                   charset = contentType.charset(charset);
                               }
                               String str=requestbuffer.readString(charset);
                               encodeString=encodeFromJNI(str);
//                              Timber.tag("加密前:").w(decodeFromJNI("D30653567F214DE750AAEBCA4ACAA49673DDF286169EAB77F448297A2D8C58D0"));
                           } catch (IOException e) {
                               e.printStackTrace();
                           }
                       }
                        Request.Builder builder=request.newBuilder();
                        String channelId= DataHelper.getStringSF(context, AppConstant.BAIDU_PUSH_CHANELID);
                        if(!TextUtils.isEmpty(channelId)){
                            builder.addHeader("City-Id","63");
                            builder.addHeader("Client-Id",channelId);
                        }
                       if (TextUtils.isEmpty(encodeString)){
                           return builder.build();
                       }else {
                           return builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), encodeString))
                                   .build();
                       }


    }

    public static native String encodeFromJNI(String orgin);
    public static native String decodeFromJNI(String des);
}
